#include "stdafx.h"
#include "base/file/win_file.h"

WinFile::WinFile()
: m_pVerBuffer(NULL)
{

}

WinFile::~WinFile()
{
    if(NULL != m_pVerBuffer) {
        delete [] m_pVerBuffer;
        m_pVerBuffer = NULL;
    }
}

bool
WinFile::Load(const TCHAR *pFilePath)
{
    if(NULL == pFilePath) {
        return false;
    }

    m_hFile.Set(::CreateFile(pFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0));
    if(NULL == m_hFile) {
        return false;
    }

    if(NULL != m_pVerBuffer) {
        delete [] m_pVerBuffer;
        m_pVerBuffer = NULL;
    }

    m_strFile = pFilePath;

    return true;
}

CString
WinFile::GetValue(const CString &strKey)
{
    if(NULL == m_hFile) {
        return _T("");
    }

    if(NULL == m_pVerBuffer) {
        DWORD nHandle = 0;
        DWORD nVerBufSize = GetFileVersionInfoSize(m_strFile.GetBuffer(), &nHandle);
        if(0 == nVerBufSize) {
            return _T("");
        }

        m_pVerBuffer = new char[nVerBufSize + 1];
        if(!GetFileVersionInfo(m_strFile.GetBuffer(), nHandle, nVerBufSize, m_pVerBuffer)) {
            delete [] m_pVerBuffer;
            m_pVerBuffer = NULL;
            return _T("");
        }
        
        UINT nLangSize = 0;
        VerQueryValue(m_pVerBuffer, _T("\\VarFileInfo\\Translation"), (LPVOID *)&m_pVerLang, &nLangSize);

        if(0 == nLangSize) {
            m_pVerLang = NULL;
        }
    }

    CString strQueryInfo;
    strQueryInfo.Format(_T("\\StringFileInfo\\%04x%04x\\%s"), ::GetSystemDefaultLangID(), 0x04B0, strKey);

    LPVOID pValue = NULL;
    UINT nSize = 0;
    if(VerQueryValue(m_pVerBuffer, strQueryInfo, &pValue, &nSize) && 0 != nSize) {
        return (TCHAR *)pValue;
    }

    if(NULL == m_pVerLang) {
        return _T("");
    }

    strQueryInfo.Format(_T("\\StringFileInfo\\%04x%04x\\%s"), m_pVerLang->wLanguage, m_pVerLang->wCodePage, strKey);
    if(VerQueryValue(m_pVerBuffer, strQueryInfo, &pValue, &nSize) && 0 != nSize) {
        return (TCHAR *)pValue;
    }

    return _T("");
}